CREATE DATABASE wewant CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE wewant;

-- Users (petition owners, admins)
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(200),
  email VARCHAR(255) UNIQUE,
  password_hash VARCHAR(255), -- nullable for oauth or non-registered creators
  role ENUM('user','admin') DEFAULT 'user',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

-- Petitions
CREATE TABLE petitions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NULL,
  slug VARCHAR(255) UNIQUE, -- friendly URL, e.g. save-the-park
  title VARCHAR(255),
  description TEXT,
  goal INT DEFAULT 1000,
  image_url VARCHAR(512) DEFAULT NULL,
  category VARCHAR(100),
  target VARCHAR(255), -- e.g. "Premier of NSW"
  is_published TINYINT(1) DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NULL,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB;

-- Signatures (signers)
CREATE TABLE signatures (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  petition_id INT NOT NULL,
  name VARCHAR(200),
  email VARCHAR(255),
  comment TEXT,
  is_verified TINYINT(1) DEFAULT 0,
  verify_token VARCHAR(64) DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  verified_at TIMESTAMP NULL,
  ip_address VARCHAR(45) DEFAULT NULL,
  user_agent VARCHAR(255) DEFAULT NULL,
  FOREIGN KEY (petition_id) REFERENCES petitions(id) ON DELETE CASCADE,
  INDEX (petition_id),
  INDEX (email)
) ENGINE=InnoDB;

-- Petition updates (creator posts)
CREATE TABLE petition_updates (
  id INT AUTO_INCREMENT PRIMARY KEY,
  petition_id INT NOT NULL,
  title VARCHAR(255),
  body TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (petition_id) REFERENCES petitions(id) ON DELETE CASCADE
) ENGINE=InnoDB;
